package com.example.apigateway.utils;

import org.apache.commons.lang.reflect.FieldUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.concurrent.Callable;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2018-06-23
 **/

public final class Rests {

    private static final Logger LOGGER = LoggerFactory.getLogger(Rests.class);

    private Rests(){};

    private static DefaultHandler defaultHanlder = new DefaultHandler();


    public static <T> T exc(Callable<T> callable){
        return exc(callable,defaultHanlder);
    }

    public static <T> T exc(Callable<T> callable, ResultHandler handler) {
        T result = sendReq(callable);
        return handler.handler(result);
    }

    public static class DefaultHandler implements ResultHandler{
        @Override
        public <T> T handler(T result) {
            int code = 1;
            String msg = "";
            try {
                code = (Integer) FieldUtils.readDeclaredField(result,"code",true);
                msg = (String) FieldUtils.readDeclaredField(result,"msg",true);

            } catch(Exception e) {

            }
            if(code!=0) {
                throw new RestException("Get erroNo " + code + " when execute rest call with errorMsg " +msg);
            }
            return result;
        }
    }

    public interface ResultHandler{
        <T> T handler(T result);
    }

    public static <T> T sendReq(Callable<T> callable) {
        T result = null;
        try {
            result = callable.call();
        } catch (Exception e) {
            throw new RestException("sendReq error by " + e.getMessage());
        } finally {
            LOGGER.info("result={}", result);
        }

        return result;
    }

    public static String toUrl(String serviceName, String path) {
        return "http://"+serviceName+path;
    }
}






